import 'package:flutter/material.dart';
import '../../api/list_color.dart';
import '../../api/list_color_group.dart';
import '../../definitions/color.dart';
import '../../definitions/system_aud.dart';
import '../../model/color.dart';
import '../../widgets/choice_question_practice.dart';
import '../../widgets/color_practice_option_card.dart';
import '../../wrappers/safe-area.dart';

class ColorPracticePage extends StatefulWidget {
  const ColorPracticePage({super.key});

  @override
  State<ColorPracticePage> createState() => _ColorPracticePageState();
}

class _ColorPracticePageState extends State<ColorPracticePage> {
  List<ColorInfo> colorList = [];

  void loadData() {
    Future.wait([listColorGroup(), listColor()]).then((res) {
      List<ColorGroup> colorGroupList = res[0] as List<ColorGroup>;
      List<ColorInfo> colorInfoList = res[1] as List<ColorInfo>;
      setState(() {
        colorList = colorGroupList
            .map<FixedColorGroup>((group) => FixedColorGroup(
                id: group.id,
                title: group.title,
                colorList: colorInfoList
                    .where((color) => color.group.contains(group.id))
                    .toList()))
            .firstWhere((group) => group.id == 'common')
            .colorList;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return SafeAreaPageWrapper(
        padding: EdgeInsets.all(12),
        child: colorList.isEmpty
            ? Center(
                child: Text('数据加载中'),
              )
            : ChoiceQuestionPractice<ColorInfo>(
                totalOptions: colorList,
                tip: Text(
                  '请选出你听到的颜色',
                  style: TextStyle(fontSize: 22),
                ),
                tipAud: SystemAud.colorPracticeQuestion.value,
                renderQuestion:
                    (ColorInfo answer, List<ColorInfo> options, bool hasFocus) {
                  return Text(
                    '请选择${answer.value}（${answer.pinYin}）',
                    style: TextStyle(
                        color: hasFocus ? SchemeColor.seedColor.value : null,
                        fontFamily: 'PinYin',
                        fontSize: 22),
                  );
                },
                renderOption: (ColorInfo option, bool hasFocus) {
                  return Container(
                    alignment: Alignment.center,
                    child: ColorPracticeOptionCard(
                      color: option,
                      hasFocus: hasFocus,
                    ),
                  );
                },
                getQuestionAud: (ColorInfo answer, List<ColorInfo> options) {
                  return answer.aud;
                },
              ));
  }
}
